package com.huike.interceptor;

import com.huike.web.service.TokenService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录校验的拦截器
 */
@Component
@Slf4j
public class JwtTokenInInterceptor implements HandlerInterceptor {

    @Autowired
    TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //1. 获取请求头中的token令牌（Authorization）
        String token1 = request.getHeader("Authorization");
        String token2 = tokenService.getToken(request);

        //2. 解析jwt，如果报错就返回false，如果不报错就返回true
        try {
            Claims claims = tokenService.parseToken(token1);
            //表示放行
            log.info("token解析成功：{}", claims);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("token解析失败：{}", token1);
            //表示不放行，响应401状态码
            response.setStatus(401);
            return false;
        }
    }
}
